package com.whmnx.home.ui.model;

import android.app.Application;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alipay.sdk.app.PayTask;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.qcloud.ugckit.utils.ToastUtil;
import com.whmnx.base.bean.AddressBean;
import com.whmnx.base.bean.OrderBean;
import com.whmnx.base.bean.PayBean;
import com.whmnx.base.bean.PayResult;
import com.whmnx.base.bean.ShopListBean;
import com.whmnx.base.bean.WeixinBean;
import com.whmnx.base.constants.Constants;
import com.whmnx.base.constants.EventConstants;
import com.whmnx.base.http.CallBack;
import com.whmnx.base.http.HttpClient;
import com.whmnx.base.router.RouterActivityPath;
import com.whmnx.base.utils.ImageUtil;
import com.whmnx.home.R;
import com.whmnx.home.databinding.FragmentConfirmOrder4Binding;
import com.whmnx.home.ui.activity.ConfirmOrderActivity3;
import com.whmnx.home.ui.adapter.OrderListAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.bus.RxSubscriptions;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

/**
 * author : huang
 * date   : 2020/10/19 0019 10:32
 * version: 1.0
 * @author Administrator
 */
public class ConfirmOrderModel3 extends ToolbarViewModel{
    public ObservableField<String> address = new ObservableField<>("");
    public ObservableField<String> totalAmount = new ObservableField<>("");
    public ObservableField<String> remark = new ObservableField<>("");
    public ObservableField<String> redBagMoney = new ObservableField<>("");

    private List<OrderBean.ShopModelBean.ProductListBean> productList = new ArrayList<>();
    private ConfirmOrderActivity3 mFragment;
    private FragmentConfirmOrder4Binding mBinding;
    private OrderListAdapter mOrderListAdapter;
    private OrderBean mOrderBean;
    private AddressBean addressBean;
    private int payType;
    private boolean flag;
    private List<OrderBean.GroupInfoListBean> groupInfoList;

    public IWXAPI mWxApi;


    public ConfirmOrderModel3(@NonNull Application application) {
        super(application);
    }

    private Disposable subscribe;

    public void initToolbar(ConfirmOrderActivity3 confirmOrderFragment, FragmentConfirmOrder4Binding binding, OrderBean orderBean) {
        this.mOrderBean = orderBean;
        this.mFragment = confirmOrderFragment;
        this.mBinding = binding;
        setTitleText("确认订单");

        mBinding.rvShop.setLayoutManager(new LinearLayoutManager(mFragment));
        mBinding.rvShop.setItemAnimator(new DefaultItemAnimator());
        mOrderListAdapter = new OrderListAdapter(mFragment);
        mBinding.rvShop.setAdapter(mOrderListAdapter);

        if (orderBean != null) {
            productList = orderBean.getShopModel().get(0).getProductList();
            mOrderListAdapter.replaceAll(orderBean.getShopModel(), true);
            totalAmount.set("￥" + orderBean.getTotalAmount() + "");
          //  totalAmount.set(orderBean.getTotalAmount() + "");
          //  redBagMoney.set("￥" + 0);

            groupInfoList = orderBean.getGroupInfoList();
            if (groupInfoList != null && groupInfoList.size() > 0){
                mBinding.rlTan.setVisibility(View.VISIBLE);
                mBinding.view.setVisibility(View.VISIBLE);
                ImageUtil.setImage(mBinding.ivTan,groupInfoList.get(0).getUserInfo_Image());
            }
        }else {
            List<String> list2 = Constants.list;
            initData(list2);
        }

        initView();
    }



    @Override
    public void onCreate() {
        super.onCreate();
        mWxApi = WXAPIFactory.createWXAPI(mFragment, Constants.WECHAT_ID, false);
        mWxApi.registerApp(Constants.WECHAT_ID);
         selectType(0);
    }

    private void selectType(int type) {
        payType = type;
        switch (type){
            case 0:
                mBinding.ivWxSelect.setImageResource(R.mipmap.check1);
                mBinding.ivZfbSelect.setImageResource(R.mipmap.check2);
                break;
            case 1:
                mBinding.ivWxSelect.setImageResource(R.mipmap.check2);
                mBinding.ivZfbSelect.setImageResource(R.mipmap.check1);
                break;
            default:
        }
    }

    private void initData(List<String> list) {
        Map<String, Object> params = new HashMap<>();
        params.put("ids",list);
      //  params.put("userInfo_Id",SPUtils.getInstance().getString(Constants.USERID));

        HttpClient.post(mFragment, Constants.SHOPCARTORDER, params,new CallBack<OrderBean>() {
            @Override
            public void onSuccess(OrderBean orderBean) {
                mOrderBean = orderBean;
             //   productList = orderBean.getShopModel().get(0).getProductList();
                mOrderListAdapter.replaceAll(orderBean.getShopModel());

                totalAmount.set("￥" + orderBean.getTotalAmount() + "");
                redBagMoney.set("¥ 0");
            }
        });

    }

    private void initView() {
        subscribe = RxBus.getDefault().toObservable(Object.class)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object object){
                        if (object.equals(EventConstants.WEIXIN)){  //支付回调
                            finish();
                          //  aliPayNotify();
                        }else if (AddressBean.class.isInstance(object)){
                            flag = true;
                            addressBean = (AddressBean)object;
                            mBinding.includeAddress.setVisibility(View.VISIBLE);
                            TextView tvName = mBinding.includeAddress.findViewById(R.id.tv_name);
                            TextView tvPhone = mBinding.includeAddress.findViewById(R.id.tv_phone);
                            TextView tvAddress = mBinding.includeAddress.findViewById(R.id.tv_address);
                            tvName.setText("收货人: " + addressBean.getAddress_Name());
                            tvPhone.setText(addressBean.getAddress_Mobile());
                            if (TextUtils.isEmpty(addressBean.getAddress_LabelDetail())){
                                tvAddress.setText("收货地址: " +  addressBean.getAddress_Detailed());
                            }else {
                                tvAddress.setText("收货地址: " +  addressBean.getAddress_Detailed() + " " + addressBean.getAddress_LabelDetail());
                            }

                        }
                        //解除注册
                       // RxSubscriptions.remove(subscribe);
                    }
                });
        RxSubscriptions.add(subscribe);
    }



    //添加地址
    public BindingCommand OnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            ARouter.getInstance().build(RouterActivityPath.User.PAGER_USERDETAIL).navigation();
        }
    });

    public BindingCommand zfOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            selectType(0);
        }
    });

    public BindingCommand  wxOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            selectType(1);
        }
    });


    private List<OrderBean.ShopModelBean> shopModel;
    private ShopListBean.ProductListBean productListBean;
    private List<OrderBean.ShopModelBean.ProductListBean> productList1;
    private double aDouble;
    private double aDouble1;
    //提交订单
    public BindingCommand OnClickCommand2 = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (!flag){
                ToastUtils.showShort("请选添加地址");
                return;
            }
            //总的 第一个集合
            List<ShopListBean> shopListBean = new ArrayList<>();
            //第二个集合
            List<ShopListBean.ProductListBean> productListBean = new ArrayList<>();

         //   ShopListBean.ProductListBean productListBean2 = new ShopListBean.ProductListBean();
          //  productListBean.add(new ShopListBean.ProductListBean());


            if (productList.size() > 0) {
                productListBean.add(new ShopListBean.ProductListBean());
                productListBean.get(0).setProduct_Id(productList.get(0).getProduct_Id());
                productListBean.get(0).setProduct_Name(productList.get(0).getProduct_Name());
                productListBean.get(0).setProduct_Image(productList.get(0).getProduct_Image());
                productListBean.get(0).setProduct_SPEC(productList.get(0).getProduct_SPEC());
                productListBean.get(0).setProduct_Price(productList.get(0).getProduct_Price() + "");
                productListBean.get(0).setProduct_Num(productList.get(0).getProduct_Num());
            }else {
                shopModel = mOrderBean.getShopModel();
                for (int i = 0; i < shopModel.size(); i++) {
                    double money = 0;
                    productList1 = shopModel.get(i).getProductList();
                    List<ShopListBean.ProductListBean> productList2 = new ArrayList<>();
                    for (int i1 = 0; i1 < productList1.size(); i1++) {
                        ShopListBean.ProductListBean productListBean2 = new ShopListBean.ProductListBean();
                        productListBean2.setProduct_Id(productList1.get(i1).getProduct_Id());
                        productListBean2.setProduct_Name(productList1.get(i1).getProduct_Name());
                        productListBean2.setProduct_Image(productList1.get(i1).getProduct_Image());
                        productListBean2.setProduct_SPEC(productList1.get(i1).getProduct_SPEC());
                        productListBean2.setProduct_Price(productList1.get(i1).getProduct_Price() + "");
                        productListBean2.setProduct_Num(productList1.get(i1).getProduct_Num());
                        productList2.add(productListBean2);
                        aDouble = productList1.get(i1).getProduct_Num() * (double)productList1.get(i1).getProduct_Price();
                     //   aDouble1 = productList1.get(i1).getProduct_Num() * (double) productList1.get(i1).getProduct_Price();
                        money += aDouble;
                    }

                    shopListBean.add(new ShopListBean());
                    shopListBean.get(i).setProductList(productList2);
                    shopListBean.get(i).setMId(shopModel.get(i).getMId());
                    shopListBean.get(i).setMoney(money + "");
                    shopListBean.get(i).setRedBagMoney(shopModel.get(i).getRedBagMoney() + "");
                  //  shopListBean.get(i).setRemark(remark.get());
                }



              /*  for (OrderBean.ShopModelBean.ProductListBean listBean : shopModel.get(0).getProductList()) {
                    ShopListBean.ProductListBean productListBean2 = new ShopListBean.ProductListBean();
                    productListBean2.setProduct_Id(listBean.getProduct_Id());
                    productListBean2.setProduct_Name(listBean.getProduct_Name());
                    productListBean2.setProduct_Image(listBean.getProduct_Image());
                    productListBean2.setProduct_SPEC(listBean.getProduct_SPEC());
                    productListBean2.setProduct_Price(listBean.getProduct_Price() + "");
                    productListBean2.setProduct_Num(listBean.getProduct_Num());
                    productList2.add(productListBean2);
                }*/
               // shopListBean.add(new ShopListBean());
              //  shopListBean.get(0).setProductList(productList2);

               // shopListBean.addAll(productList);
            }


            ShopListBean.AddressBean2 addressBean2 = new ShopListBean.AddressBean2();
            addressBean2.setAddress_Id(addressBean.getAddress_Id());
            addressBean2.setAddress_Name(addressBean.getAddress_Name());
            addressBean2.setAddress_Mobile(addressBean.getAddress_Mobile());
            addressBean2.setAddress_Detailed(addressBean.getAddress_Detailed());
            addressBean2.setAddress_Label(addressBean.getAddress_Label());

                if (productList.size() > 0) {  //
                    shopListBean.add(new ShopListBean());
                    shopListBean.get(0).setProductList(productListBean);
                    shopListBean.get(0).setMId(mOrderBean.getShopModel().get(0).getMId());
                    shopListBean.get(0).setMoney(mOrderBean.getTotalAmount() + "");
                    shopListBean.get(0).setRedBagMoney(mOrderBean.getShopModel().get(0).getRedBagMoney() + "");
                    shopListBean.get(0).setRemark(remark.get());
                }else {  //购物车  多商家


                }


            Map<String, Object> params = new HashMap<>();
            params.put("address",addressBean2);
            params.put("shopModel",shopListBean);
            params.put("userInfo_Id", SPUtils.getInstance().getString(Constants.USERID));
            if (null != groupInfoList && groupInfoList.size() > 0){
                params.put("isGroup",1);
                params.put("groupNo",groupInfoList.get(0).getOrderGroup_No());  //3e7ca10a-e441-408d-8e93-881f7fbc4741

            }else {
                params.put("isGroup",0);
            }

            params.put("totalAmount", mOrderBean.getTotalAmount());
            //1 是 威信 2 是支付宝
            params.put("payType", payType + 1);

            if (payType == 0){
                HttpClient.post(mFragment, Constants.ADDORDER, params,new CallBack<PayBean>() {
                    @Override
                    public void onSuccess(PayBean payBean) {
                            zhiAliPay(payBean.getSign());
                    }
                });
            }else {
               HttpClient.post(mFragment, Constants.ADDORDER, params,new CallBack<WeixinBean>() {
                @Override
                public void onSuccess(WeixinBean weixinBean) {
                    PayReq req = new PayReq();
                    req.appId = weixinBean.getSign().getAppId();
                    req.partnerId = weixinBean.getSign().getPartnerId();
                    req.prepayId = weixinBean.getSign().getPrepayId();
                    req.nonceStr = weixinBean.getSign().getNonceStr();
                    req.timeStamp = weixinBean.getSign().getTimeStamp();
                    req.packageValue = weixinBean.getSign().getPackageValue();
                    req.sign = weixinBean.getSign().getSign();
                    //  req.extData = "0.02";
                    mWxApi.sendReq(req);
                }
             });
            }
        }
    });

    private void zhiAliPay(String sign) {
        Runnable payRunnable = () -> {
            PayTask alipay = new PayTask(mFragment);
            PayResult payResult = new PayResult((Map<String, String>) alipay.payV2(sign, true));
            /**
             对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
             */
            final String resultStatus = payResult.getResultStatus();// 同步返回需要验证的信息
            mFragment.runOnUiThread(() -> {
                // 判断resultStatus 为9000则代表支付成功
                if (TextUtils.equals(resultStatus, "9000")) {
                    // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                    ToastUtil.toastShortMessage("支付成功");
                    finish();
                  //  aliPayNotify();
                   // getTradingInfo();
                } else {
                    ToastUtil.toastShortMessage("支付失败");
                }
            });
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private void aliPayNotify() {
        Map<String, Object> params = new HashMap<>();
        HttpClient.post(mFragment, Constants.ALIPAYNOTIFY, params,new CallBack<PayBean>() {
            @Override
            public void onSuccess(PayBean payBean) {
               finish();
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxSubscriptions.remove(subscribe);
    }
}
